<?php
namespace App\Webdisk\Utils;
class SysInfo {
    static function getNetworkInterfaces() {
        exec('cat /proc/net/dev | sed \'1,2d\' | awk \'{print $1}\' | awk -F: \'{print $1}\'', $res);
        return $res;
    }


    static function getNetworkInterfaceInfo($interface_name) {
        $cmd = 'cat /proc/net/dev | sed \'1,2d\' | grep -E \'^\\s+?'. $interface_name .':\' | awk \'{printf("{\"recv\":%d, \"send\":%d}",$2,$10)}\'';
        exec($cmd, $res);
        return json_decode($res[0], true);
    }

    static function getNetworkInterfacesInfo($interface_names = '') {
        $data = [];
        if ($interface_names == '') {
            $interface_names = self::getNetworkInterfaces();
        }
        if (gettype($interface_names) == 'string') {
            $interface_names = [$interface_names];
        }
        foreach ($interface_names as $itf) {
            $data[$itf][0] = self::getNetworkInterfaceInfo($itf);
        }
        usleep(200000);
        foreach ($interface_names as $itf) {
            $data[$itf][1] = self::getNetworkInterfaceInfo($itf);
        }
        $res = [];
        foreach ($data as $itf => &$value) {
            $res[$itf]['recv_total'] = $value[0]['recv'];
            $res[$itf]['send_total'] = $value[0]['send'];
            $res[$itf]['recv_speed'] = ($value[1]['recv'] - $value[0]['recv'])*5;
            $res[$itf]['send_speed'] = ($value[1]['send'] - $value[0]['send'])*5;
            unset($value);
        }
        return $res;
    }
}
